package com.zcmob.web.admanagement.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jackson.map.ObjectMapper;

import com.zcmob.web.admanagement.util.FileUtils;
import com.zcmob.web.admanagement.util.PropsUtils;

public class ProgressUploadImageServlet extends HttpServlet {
    private ObjectMapper mapper = new ObjectMapper();
    
    /**
     * 
     */
    private static final long serialVersionUID = 8610105187693771753L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Cache-Control", "no-store");// 禁止浏览器缓存
        resp.setHeader("Pragrma", "no-cache");// 禁止浏览器缓存
        resp.setDateHeader("Expires", 0);// 禁止浏览器缓存
        resp.setCharacterEncoding("UTF-8");
        System.out.println("=================");
        UploadStatus status = (UploadStatus) req.getSession(true).getAttribute("uploadstatus");
        if (status == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("percent", 0);
            result.put("status", "processing");
            mapper.writeValue(resp.getWriter(), result);
            return;
        }
        long startTime = status.getStartTime();
        long currentTime = System.currentTimeMillis();
        long time = (currentTime - startTime) / 1000 + 1; // 已传输的时间 单位：s
        double velocity = ((double) status.getByteRead()) / (double) time;// 传输速度
        // bytes/s
        double totalTime = status.getContentLength() / velocity;// 估计时间
        double timeLeft = totalTime - time;// 剩余时间
        int percent = (int) (100 * (double) status.getByteRead() / (double) status.getContentLength());// 已完成的百分比
        double length = ((double) status.getByteRead() / 1024 / 1024);// 已完成数
        // 单位：M
        double totalLength = ((double) status.getContentLength()) / 1024 / 1024;// 总长度：
        // 单位：M
        // 格式:
        // 百分比||已完成数(M)||文件总长度(M)||传输速率(K)||已用时间(S)||估计总时间(S)||估计剩余时间(S)||正在上传第几个文件
        String value = percent + "||" + length + "||" + totalLength + "||" + velocity + "||" + time + "||" + totalTime
                + "||" + timeLeft + "||" + status.getItems();
        
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("percent", percent);
        result.put("status", "processing");
        result.put("validinfo", req.getSession(true).getAttribute("validinfo") == null ? "" : 
            req.getSession(true).getAttribute("validinfo"));
        req.getSession(true).removeAttribute("validinfo");
        System.out.println("current: " + length + " total: " + totalLength);
        if (length >= totalLength) {
            result.put("status", "finished");
            result.put("jpgPath", req.getSession(true).getAttribute("tmpImageFilePath"));
            result.put("jpgName", req.getSession(true).getAttribute("tmpImageFileName"));
            req.getSession(true).removeAttribute("tmpImageFilePath");
            req.getSession(true).removeAttribute("tmpImageFileName");
            req.getSession(true).removeAttribute("uploadstatus");
        }
        
        mapper.writeValue(resp.getWriter(), result);

    }
    
    public static List<String> validJpg = new ArrayList<String>();
    
    static {

        validJpg.add("320*480");
        validJpg.add("480*320");
        validJpg.add("480*800");
        /*        validJpg.add("480*848");
        validJpg.add("480*854");
        validJpg.add("640*960");*/
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UploadStatus status = new UploadStatus();// 上传状态
        UploadListener listener = new UploadListener(status);// 监听器
        req.getSession(true).setAttribute("uploadstatus", status);
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());// 解析
        upload.setProgressListener(listener);// 设置上传的listener

        try {
            // upload.setSizeMax(10*1024*1024);//设置大小，超出则抛出FileUploadException
            List itemList = upload.parseRequest(req);
            for (Iterator it = itemList.iterator(); it.hasNext();) {
                FileItem item = (FileItem) it.next();
                if (!item.isFormField())// 如果是非表单数据
                {
                    if (item.getName().length() <= 0)
                        return;// 表示后面的文件域没有选中文件

                    this.log("file size: " + ((double) item.getSize() / 1024 / 1024) + "M");
                    this.log("file type：" + item.getContentType());// 文件类型
                    this.log("File: " + item.getName());

                    String extension = item.getName().substring(item.getName().lastIndexOf("."));
                    this.log("File Extension：" + extension);

                    if (item.getSize() > 200 * 1024) {
                        req.getSession(true).setAttribute("validinfo", "图片已超过200k");
                        return;
                    }
                    
                    if (!extension.equalsIgnoreCase(".jpg")) {
                        req.getSession(true).setAttribute("validinfo", "请使用jpg图片");
                        return;
                    }
                    
                    String tmpFileName = UUID.randomUUID().toString() + ".jpg";
                    String filePath = PropsUtils.getProperty("jpgtmpserverpath") + tmpFileName;
                    item.write(new File(filePath));
                    /*if (!validJpg.contains(FileUtils.getImageResolution(filePath))) {
                        req.getSession(true).setAttribute("validinfo", "分辨率有误哦");
                        new File(filePath).deleteOnExit();
                        return;
                    }*/
                    
                    req.getSession(true).setAttribute("tmpImageFilePath", PropsUtils.getProperty("jpgtmphttppath") + tmpFileName);
                    req.getSession(true).setAttribute("tmpImageFileName", tmpFileName);
                    
                    

                    
                }
            }
        } catch (Exception e) {
            this.log("上传发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        String dir = getClass().getClassLoader().getResource("/").getPath();
        System.out.println(dir);
        try {
            PropsUtils.load2SystemProperties(new File(dir + "env.properties"));
        } catch (IOException e) {
            
            throw new ServletException(e);
        }
        super.init(config);
    }
}
